<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm">
      <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
          <h1 class="text-xl font-bold text-blue-600">AI智能市场</h1>
          <div class="text-sm text-gray-500 px-2 border-l border-gray-300">专业服务</div>
        </div>
        <div class="flex items-center space-x-4">
          <button
            class="text-gray-600 hover:text-blue-600 cursor-pointer !rounded-button whitespace-nowrap"
          >
            <el-icon>
              <ShoppingCart />
            </el-icon>
            <span class="ml-1">购物车</span>
          </button>
          <button
            class="text-gray-600 hover:text-blue-600 cursor-pointer !rounded-button whitespace-nowrap"
          >
            <el-icon>
              <User />
            </el-icon>
            <span class="ml-1">个人中心</span>
          </button>
        </div>
      </div>
    </header>
    <!-- 侧边导航 -->
    <div class="container mx-auto px-4 flex mt-4">
      <!-- 主内容区 -->
      <main class="flex-1">
        <!-- 标题和操作区 -->
        <div class="mb-6 flex justify-between items-center">
          <h2 class="text-2xl font-bold text-gray-800">我的知识库</h2>
          <button
            @click="showNewKnowledgeBaseDialog = true"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center cursor-pointer !rounded-button whitespace-nowrap"
          >
            <el-icon class="mr-2">
              <Plus />
            </el-icon>
            新建知识库
          </button>
        </div>
        <!-- 搜索和筛选 -->
        <div class="mb-6 flex">
          <div class="relative flex-1">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索知识库名称或内容"
              class="w-full py-2 px-4 pr-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <button @click="searchKnowledgeBase" class="absolute right-3 top-2.5 text-gray-400 cursor-pointer">
              <el-icon>
                <Search />
              </el-icon>
            </button>
          </div>
        </div>
        <!-- 知识库列表 -->
        <div
          v-if="filteredKnowledgeBases.length > 0"
          class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
        >
          <div
            v-for="(kb, index) in filteredKnowledgeBases"
            :key="index"
            class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow"
          >
            <div class="p-4 border-b border-gray-100">
              <div class="flex justify-between items-start">
                <h3 class="text-lg font-medium text-gray-800 mb-1">{{ kb.name }}</h3>
                <el-dropdown trigger="click">
                  <button class="text-gray-400 hover:text-gray-600 cursor-pointer">
                    <el-icon>
                      <MoreFilled />
                    </el-icon>
                  </button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="viewKnowledgeBase(kb)">
                        <el-icon class="mr-1">
                          <View />
                        </el-icon>
                        查看
                      </el-dropdown-item>
                      <el-dropdown-item @click="editKnowledgeBase(kb)">
                        <el-icon class="mr-1">
                          <EditPen />
                        </el-icon>
                        编辑
                      </el-dropdown-item>
                      <el-dropdown-item @click="showDeleteConfirm(kb)" divided>
                        <span class="text-red-500">
                          <el-icon class="mr-1">
                            <Delete />
                          </el-icon>
                          删除
                        </span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="text-sm text-gray-500 mb-2">{{ kb.desc }}</div>
            </div>
            <div class="p-4 bg-gray-50">
              <div class="flex justify-between items-center text-sm">
                <div class="flex items-center space-x-4">
                  <div class="flex items-center">
                    <el-icon class="mr-1 text-blue-500">
                      <Document />
                    </el-icon>
                    <span>{{ kb.documentCount }} 文档</span>
                  </div>
                  <div class="flex items-center">
                    <el-icon class="mr-1 text-green-500">
                      <Timer />
                    </el-icon>
                    <span>{{ formatDate(kb.createTime) }}</span>
                  </div>
                </div>
                <div class="text-xs px-2 py-1 rounded-full" :class="getStatusClass(kb.knowledgeType)">
                  {{ getKnowledgeTypeText(kb.knowledgeType) }}
                </div>
              </div>
              <div class="mt-3 flex items-center text-sm text-gray-500">
                <el-icon class="mr-1">
                  <Refresh />
                </el-icon>
                <span>最近更新: {{ formatDate(kb.updateTime) }}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 空状态 -->
        <div v-else-if="loading" class="bg-white rounded-lg shadow-sm p-8 text-center">
          <el-skeleton :rows="3" animated />
        </div>
        <div v-else class="bg-white rounded-lg shadow-sm p-8 text-center">
          <div class="flex justify-center mb-4">
            <el-icon class="text-6xl text-gray-300">
              <Folder />
            </el-icon>
          </div>
          <h3 class="text-lg font-medium text-gray-800 mb-2">暂无知识库</h3>
          <p class="text-gray-500 mb-4">您还没有创建任何知识库，点击"新建知识库"按钮开始创建</p>
          <button
            @click="showNewKnowledgeBaseDialog = true"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer !rounded-button whitespace-nowrap"
          >
            <el-icon class="mr-2">
              <Plus />
            </el-icon>
            新建知识库
          </button>
        </div>
        <!-- 分页 -->
        <div v-if="totalKnowledgeBases > 0" class="mt-8 flex justify-center">
          <el-pagination
            :total="totalKnowledgeBases"
            :page-size="pageSize"
            :current-page="currentPage"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </main>
    </div>
    <!-- 新建知识库对话框 -->
    <el-dialog v-model="showNewKnowledgeBaseDialog" title="新建知识库" width="500px">
      <el-form :model="newKnowledgeBase" label-width="100px">
        <el-form-item label="知识库名称" required>
          <el-input v-model="newKnowledgeBase.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newKnowledgeBase.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入知识库描述"
          />
        </el-form-item>
        <el-form-item label="知识库类型">
          <el-select v-model="newKnowledgeBase.knowledgeType" placeholder="请选择知识库类型" class="w-full">
            <el-option label="文档知识库" :value="KnowledgeType.DOCUMENT" />
            <el-option label="网页知识库" :value="KnowledgeType.WEB_PAGE" />
            <el-option label="图片知识库" :value="KnowledgeType.IMAGE" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showNewKnowledgeBaseDialog = false">取消</el-button>
          <el-button type="primary" @click="createKnowledgeBase" :disabled="!newKnowledgeBase.name"
            >创建</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 编辑知识库对话框 -->
    <el-dialog v-model="showEditKnowledgeBaseDialog" title="编辑知识库" width="500px">
      <el-form :model="editingKnowledgeBase" label-width="100px">
        <el-form-item label="知识库名称" required>
          <el-input v-model="editingKnowledgeBase.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="editingKnowledgeBase.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入知识库描述"
          />
        </el-form-item>
        <el-form-item label="知识库类型">
          <el-select
            v-model="editingKnowledgeBase.knowledgeType"
            placeholder="请选择知识库类型"
            class="w-full"
            disabled
          >
            <el-option label="文档知识库" :value="KnowledgeType.DOCUMENT" />
            <el-option label="网页知识库" :value="KnowledgeType.WEB_PAGE" />
            <el-option label="图片知识库" :value="KnowledgeType.IMAGE" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditKnowledgeBaseDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="updateKnowledgeBase"
            :disabled="!editingKnowledgeBase.name"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 查看/编辑知识库内容对话框 -->
    <el-dialog v-model="showViewDialog" :title="viewingKnowledgeBase?.name" width="800px">
      <div class="flex flex-col h-[600px]">
        <el-input
          v-model="viewingContent"
          type="textarea"
          :rows="20"
          placeholder="请输入知识库内容"
          class="flex-1 mb-4"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showViewDialog = false">取消</el-button>
          <el-button type="primary" @click="saveKnowledgeBaseContent">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="showDeleteDialog" title="删除知识库" width="400px">
      <div class="text-center">
        <el-icon class="text-5xl text-red-500 mb-4">
          <WarningFilled />
        </el-icon>
        <p class="mb-4">确定要删除知识库 "{{ knowledgeBaseToDelete?.name }}" 吗？</p>
        <p class="text-sm text-gray-500 mb-4">此操作将永久删除该知识库及其所有文档，且无法恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteKnowledgeBase">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document,
  Setting,
  ChatDotRound,
  Picture,
  VideoPlay,
  Search,
  Plus,
  ShoppingCart,
  User,
  Lock,
  Medal,
  Wallet,
  Upload,
  Files,
  View,
  EditPen,
  Delete,
  MoreFilled,
  Timer,
  Refresh,
  WarningFilled,
  Folder,
} from '@element-plus/icons-vue'
import { useRouter1 } from '../utils/useRoute'
import { 
  createKnowledge, 
  listKnowledge, 
  deleteKnowledge as apiDeleteKnowledge, 
  updateKnowledge as apiUpdateKnowledge,
  KnowledgeType,
  KnowledgeTypeDesc
} from '../api/knowledge'

const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// 页面状态
const currentPage = ref(1)
const pageSize = ref(9)
const totalKnowledgeBases = ref(0)
const searchQuery = ref('')
const timeFilter = ref('all')
const typeFilter = ref('all')
const loading = ref(false)

// 对话框状态
const showNewKnowledgeBaseDialog = ref(false)
const showEditKnowledgeBaseDialog = ref(false)
const showDeleteDialog = ref(false)

// 表单数据
const newKnowledgeBase = ref({
  name: '',
  desc: '',
  knowledgeType: KnowledgeType.DOCUMENT,
})

const editingKnowledgeBase = ref(null)
const knowledgeBaseToDelete = ref(null)
const knowledgeBases = ref([])

// 计算属性：过滤后的知识库列表
const filteredKnowledgeBases = computed(() => {
  let result = [...knowledgeBases.value]
  
  // 类型过滤
  if (typeFilter.value !== 'all') {
    result = result.filter((kb) => kb.knowledgeType === typeFilter.value)
  }
  
  // 时间过滤
  if (timeFilter.value !== 'all') {
    const now = Date.now()
    let startTime = now
    
    if (timeFilter.value === 'week') {
      startTime = now - 7 * 24 * 60 * 60 * 1000
    } else if (timeFilter.value === 'month') {
      startTime = now - 30 * 24 * 60 * 60 * 1000
    } else if (timeFilter.value === 'quarter') {
      startTime = now - 90 * 24 * 60 * 60 * 1000
    }
    
    result = result.filter((kb) => kb.createTime >= startTime)
  }
  
  return result
})

// 方法
const handlePageChange = (page) => {
  currentPage.value = page
  fetchKnowledgeBases()
}

const formatDate = (timestamp) => {
  if (!timestamp) return '未知'
  const date = new Date(timestamp)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
}

const getStatusClass = (type) => {
  switch (type) {
    case KnowledgeType.DOCUMENT:
      return 'bg-blue-100 text-blue-800'
    case KnowledgeType.WEB_PAGE:
      return 'bg-green-100 text-green-800'
    case KnowledgeType.IMAGE:
      return 'bg-purple-100 text-purple-800'
    default:
      return 'bg-gray-100 text-gray-800'
  }
}

const getKnowledgeTypeText = (type) => {
  return KnowledgeTypeDesc[type] || '未知'
}

const showViewDialog = ref(false)
const viewingKnowledgeBase = ref(null)
const viewingContent = ref('')

const viewKnowledgeBase = (kb) => {
  viewingKnowledgeBase.value = { ...kb }
  // 在实际应用中，这里应该调用API获取知识库内容
  viewingContent.value = `# ${kb.name}\n\n${kb.desc}\n\n这里是知识库的详细内容...`
  showViewDialog.value = true
}

const saveKnowledgeBaseContent = () => {
  if (!viewingKnowledgeBase.value) return
  // 在实际应用中，这里应该调用API保存知识库内容
  ElMessage.success('保存成功')
  showViewDialog.value = false
}

const editKnowledgeBase = (kb) => {
  editingKnowledgeBase.value = { ...kb }
  showEditKnowledgeBaseDialog.value = true
}

const updateKnowledgeBase = async () => {
  if (!editingKnowledgeBase.value) return
  
  try {
    loading.value = true
    await apiUpdateKnowledge({
      knowledgeId: editingKnowledgeBase.value.id,
      name: editingKnowledgeBase.value.name,
      desc: editingKnowledgeBase.value.desc
    })
    
    ElMessage.success('知识库更新成功')
    showEditKnowledgeBaseDialog.value = false
    fetchKnowledgeBases()
  } catch (error) {
    console.error('更新知识库失败:', error)
    ElMessage.error('更新知识库失败')
  } finally {
    loading.value = false
  }
}

const showDeleteConfirm = (kb) => {
  knowledgeBaseToDelete.value = kb
  showDeleteDialog.value = true
}

const deleteKnowledgeBase = async () => {
  if (!knowledgeBaseToDelete.value) return
  
  try {
    loading.value = true
    await apiDeleteKnowledge({
      knowledgeId: knowledgeBaseToDelete.value.id
    })
    
    ElMessage.success('知识库删除成功')
    showDeleteDialog.value = false
    knowledgeBaseToDelete.value = null
    fetchKnowledgeBases()
  } catch (error) {
    console.error('删除知识库失败:', error)
    ElMessage.error('删除知识库失败')
  } finally {
    loading.value = false
  }
}

const createKnowledgeBase = async () => {
  if (!newKnowledgeBase.value.name) return
  
  try {
    loading.value = true
    await createKnowledge({
      name: newKnowledgeBase.value.name,
      desc: newKnowledgeBase.value.desc,
      knowledgeType: newKnowledgeBase.value.knowledgeType
    })
    
    ElMessage.success('知识库创建成功')
    // 重置表单
    newKnowledgeBase.value = {
      name: '',
      desc: '',
      knowledgeType: KnowledgeType.DOCUMENT,
    }
    showNewKnowledgeBaseDialog.value = false
    fetchKnowledgeBases()
  } catch (error) {
    console.error('创建知识库失败:', error)
    ElMessage.error('创建知识库失败')
  } finally {
    loading.value = false
  }
}

const searchKnowledgeBase = () => {
  fetchKnowledgeBases()
}

const fetchKnowledgeBases = async () => {
  try {
    loading.value = true
    const params = {
      keyword: searchQuery.value || undefined,
      page: {
        page: currentPage.value,
        limit: pageSize.value,
        order: 'DESC',
        field: 'createTime'
      }
    }
    
    const response = await listKnowledge(params)
    knowledgeBases.value = response.data || []
    totalKnowledgeBases.value = response.totalCount || 0
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage.error('获取知识库列表失败')
    knowledgeBases.value = []
    totalKnowledgeBases.value = 0
  } finally {
    loading.value = false
  }
}

// 页面加载时获取知识库列表
onMounted(() => {
  fetchKnowledgeBases()
})
</script>
<style scoped>
/* 修复输入框样式 */
input:focus {
  outline: none;
}
/* 去除number输入框的箭头 */
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input[type='number'] {
  -moz-appearance: textfield;
}
/* 自定义样式 */
.knowledge-base__card {
  transition: all 0.3s ease;
}
.knowledge-base__card:hover {
  transform: translateY(-2px);
}
</style>
